package com.demo.gulimall.order.mqlistener;

import com.demo.gulimall.order.entity.Order;
import com.demo.gulimall.order.service.OrderService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author Chen Yuan
 * @create 2023-07-04  14:55
 */
@Slf4j
@Component
@RabbitListener(queues = {"order.release.queue"})
public class OrderCloseListener {
	@Autowired
	private OrderService orderService;

	/**
	 * 自动解锁库存
	 */
	@RabbitHandler
	public void handleReleaseOrderClose(Order order, Message message, Channel channel) throws IOException {
		Boolean hasClose = null;
		try {
			log.info("--> 准备关闭订单 - orderSn:{}", order.getOrderSn());
			hasClose = orderService.closeOrder(order);
			if (hasClose) {
				channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
			}else {
				channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
			}
		} catch (Exception e) {
			channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
		}

	}

}
